<template>
  <div class="vue-easymde-editor">
    <textarea ref="textArea"></textarea>
  </div>
</template>
<script lang="ts" setup>
import { defineProps, defineEmits, ref, onMounted, onUnmounted, watch } from 'vue'
import EasyMDE, { Options } from 'easymde'
// 类型，属性以及事件
interface EditorProps {
  modelValue?: string
  options?: Options
}
interface EditorEvents {
  (type: 'update:modelValue', value: string): void
  (type: 'change', value: string): void
  (type: 'blur'): void
}
const props = defineProps<EditorProps>() // 传入参数
const emit = defineEmits<EditorEvents>() // 自定义事件
const textArea = ref<null | HTMLTextAreaElement>(null) // textArea Ref
let easyMDEInstance: EasyMDE | null = null
const innerValue = ref(props.modelValue || '') // 父组件传入输入值
watch(
  () => props.modelValue,
  newValue => {
    if (easyMDEInstance) {
      if (newValue !== innerValue.value) {
        easyMDEInstance.value(newValue || '')
      }
    }
  }
)
onMounted(() => {
  if (textArea.value) {
    // 组装 options
    const config: Options = {
      ...(props.options || {}),
      element: textArea.value,
      initialValue: innerValue.value
    }
    easyMDEInstance = new EasyMDE(config) // 初始化实例
    // 监控对应的事件
    easyMDEInstance.codemirror.on('change', () => {
      if (easyMDEInstance) {
        const updatedValue = easyMDEInstance.value() // 当前的值
        innerValue.value = updatedValue
        emit('update:modelValue', updatedValue)
        emit('change', updatedValue)
      }
    })
    easyMDEInstance.codemirror.on('blur', () => {
      if (easyMDEInstance) {
        emit('blur')
      }
    })
  }
})
// 销毁对应的实例
onUnmounted(() => {
  if (easyMDEInstance) {
    easyMDEInstance.cleanup()
  }
  easyMDEInstance = null
})
// 清空
const clear = () => {
  if (easyMDEInstance) {
    easyMDEInstance.value('')
  }
}
// 返回对应实例
const getMDEInstance = () => {
  return easyMDEInstance
}
// 编译器宏
// defineExpose({
//   clear,
//   getMDEInstance
// })
</script>
<style>
.vue-easymde-editor.is-invalid {
  border: 1px solid #dc3545;
}
</style>
